package com.sogo;

import android.database.Cursor;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

//import com.tseng.examples.MapTestActivity;
import com.sogo.R;
import com.sogo.FriendsListMainScreen;



import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

/*Main screen. Prompts user to login or register. Will auto login if user login in existant in the local database*/
public class LoginRegistrationScreen extends Activity {
	// Declare our Views, so we can access them later
	private EditText etUsername;
	private EditText etPassword;
	private Button btnLogin;

	private Button btnRegister;
	final int TIMEOUT_MILLISEC =30000; //30secs
    DBAdapter db = new DBAdapter(this);
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // Get the EditText and Button References
        etUsername = (EditText)findViewById(R.id.username);
        etPassword = (EditText)findViewById(R.id.password);
        btnLogin = (Button)findViewById(R.id.login_button);

        btnRegister = (Button)findViewById(R.id.register_button);
        //lblResult = (TextView)findViewById(R.id.result);
        //Local database stuff
        String username = null, password=null;
        try{//checks to see if user already exists. 
            db.open();
            Cursor c = db.getUser();
            if (c.moveToFirst())
            {
                do{
                	/*
    		        Toast.makeText(this,
    		        "id: " + c.getString(0) + "\n" + "UserName: " + c.getString(1) + "\n" +
    		        "First Name: " + c.getString(2) + "\n" + "Last Name: " + c.getString(3)
    		        + "\n" + "Email: " + c.getString(4) + "\n" + "Password: " + c.getString(5), Toast.LENGTH_LONG).show();*/
    		        username=c.getString(1);
    		        password=c.getString(5);
               }while (c.moveToNext());
            }
            db.close();
            if(username.length()!=0&&password.length()!=0)
            {
            	new verifyLogin(username,password).execute();
            	//Toast.makeText(this,"Username and password was found.", Toast.LENGTH_LONG).show();
            	
            }
        }catch(Exception e)
        {
        	
        }


        	
        btnLogin.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		new verifyLogin("","").execute(); //pass in empty username and password to be check in constructor.

			}
		});

        btnRegister.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				//registration button pushed
				Intent i=new Intent();
				i.setClassName("com.sogo","com.sogo.Registration");
				startActivity(i);
			}	
		});
        
    }
	
	
	
	
	private class verifyLogin extends AsyncTask<String,Void,Void>{
	    private ProgressDialog Dialog = new ProgressDialog(LoginRegistrationScreen.this);
	    String username;
		String password;
		
	    public verifyLogin(String username1, String password2) {
			if(username1.length()!=0&&password2.length()!=0)
			{
				username=username1;
				password=password2;
				//Log.e("login function start!", "LOGIN FUNCTION");
			
			}
			else
			{
				username = etUsername.getText().toString();
				password = etPassword.getText().toString();
			}
		}

		protected void onPreExecute() {
	        Dialog.setMessage("Please Wait Checking Credentials");
	        Dialog.show();
	    }
	
		protected Void doInBackground(String... params) {
			//int duration;
			//Toast toast;
			//Context context=getApplicationContext();
			AlertDialog.Builder dlgAlert = new AlertDialog.Builder(LoginRegistrationScreen.this);

			
			JSONArray jsonArray=null;
			if(password.length()!=32)
				password=ServerConnection.encryptPassword(password);
			//Log.i("login hash",password);
	        JSONObject json1 = new JSONObject();
	        try {
				json1.put("Username", username);
				json1.put("Password", password);
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
	        
			jsonArray=ServerConnection.CommunicateWithServer(json1,0);//0 for login
			String lastName = null;
			String firstName = null;
			String email = null;
			String userID= null;
			//String password;
			//String username;
			if(jsonArray!=null) //login successful
			{
				//Log.i("login is successful!",password);
				JSONObject json = new JSONObject();
				for(int i=0;i<jsonArray.length();i++){
					try {
						json=jsonArray.getJSONObject(i);
						//already have username and password
						//username=json.getString("FIRSTNAME");
						//password=json.getString("PASSWORD");
						lastName=json.getString("LASTNAME");
						firstName=json.getString("FIRSTNAME");
						email=json.getString("EMAIL");
						userID=json.getString("ID");
					
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
                db.open();
                long id = db.insertUser(Integer.parseInt(userID),username, firstName, lastName , email, password, "sometype");//login
                db.close();
				Intent i = new Intent(getApplicationContext(), FriendsListMainScreen.class);
                startActivity(i);
                finish();
			}
			else
			{
				Log.i("login is a failure!",password);
				
			}
			return null;
		}
	    protected void onPostExecute(Void unused) {
	        Dialog.dismiss();
	
	    }
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.mainmenu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
	    case R.id.exit:
	        finish();
	        return true;
	    case R.id.setting:
	    	Intent i=new Intent();
			i.setClassName("com.sogo","com.sogo.SettingMenu");
			startActivity(i);
	        return true;
		}
		return true;
	}
}